using System;
using System.Diagnostics;
using System.IO;
using UnityEngine;
using Debug = UnityEngine.Debug;

namespace UPA
{
    [Serializable]
    public class CLIActionArgument:ProcessActionArgument
    {
        [SerializeField]
        private string batPath;
        [SerializeField]
        private string shellPath;
        
        public string BatPath => batPath;
        public string ShellPath => shellPath;
    }
    
    [ProcessActionTemplateName("命令行程序")]
    [ProcessActionAllowMultiple]
    public class CLIAction:ProcessAction
    {
        public override string Name
        {
            get
            {
                var argument = GetArgument<CLIActionArgument>();
#if UNITY_EDITOR_WIN
                var path = argument.BatPath;
#else
                var path = argument.ShellPath;
#endif
                var filaName = string.IsNullOrWhiteSpace(path) ? "未选择" : Path.GetFileName(path);
                return $"命令行程序:{filaName}";
            }
        }

        public override Type RequiredArgument => typeof(CLIActionArgument);

        public override ProcessActionResult Execute()
        {
            var argument = GetArgument<CLIActionArgument>();
            
#if UNITY_EDITOR_WIN
            if (string.IsNullOrWhiteSpace(argument.BatPath))
#else
            if (string.IsNullOrWhiteSpace(argument.ShellPath))
#endif
            {
                return new ProcessActionResult(true);
            }

#if UNITY_EDITOR_WIN
            var fullPath = Path.Combine(Directory.GetCurrentDirectory(), argument.BatPath);
#else
            var fullPath = Path.Combine(Directory.GetCurrentDirectory(), argument.ShellPath);
#endif
            if (Path.DirectorySeparatorChar == '\\')
            {
                fullPath = fullPath.Replace('/', '\\');
            }
            else
            {
                fullPath = fullPath.Replace('\\', '/');
            }
            
#if UNITY_EDITOR_WIN
            if (!File.Exists(argument.BatPath))
#else
            if (!File.Exists(argument.ShellPath)) 
#endif
            {
                Debug.LogError($"文件不存在:{fullPath}");
                return new ProcessActionResult(false, $"文件不存在:{fullPath}");
            }
            
            Process process = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                WindowStyle = ProcessWindowStyle.Hidden,
#if UNITY_EDITOR_WIN
                FileName = "cmd",
                Arguments = $"/C \"{fullPath}\"",
#else
                FileName = "bash",
                Arguments = $"-c \"{fullPath}\"",
#endif
                WorkingDirectory = Path.GetDirectoryName(fullPath) ?? string.Empty,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            process.StartInfo = startInfo;
            process.Start();

            // 读取标准输出和错误输出
            string output = process.StandardOutput.ReadToEnd().Trim();
            string error = process.StandardError.ReadToEnd().Trim();

            // 等待脚本执行完毕
            process.WaitForExit();

            if (!string.IsNullOrWhiteSpace(output))
            {
                Debug.Log(output);
            }
            
            if (!string.IsNullOrWhiteSpace(error))
            {
                Debug.LogError(error);
                return new ProcessActionResult(false,"执行失败，相信信息请查看日志");
            }

            return new ProcessActionResult(true);
        }
    }
}